package com.ynet.middleground.riskmanage.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 项目名：ifp-user <br>
 * 包名：com.ynet.middleground.user.utils <br>
 * 类名：TransferUtil <br>
 * 描述：
 *
 * @author liulx
 * @create 2021-10-23 22:18
 */
public class TransferUtil {

    public static String keyIntegerToString(Object key) {
        return String.valueOf(key);
    }

    public static List buildValueList(List valList, Function<Map, Map> transferFunc) {
        if (valList == null || valList.size() == 0) {
            return valList;
        }
        Object first = valList.get(0);
        if (!(first instanceof List) && !(first instanceof Map)) {
            return valList;
        }
        List newList = new ArrayList();
        for (Object val : valList) {
            Map<String, Object> subResultMap = transferFunc.apply((Map)val);
            newList.add(subResultMap);
        }
        return newList;
    }

    public static Map<String, Object> generalMapProcess(Map<Object, Object> map, Function<Object, String> keyFunc) {
        Map<String, Object> resultMap = new HashMap<>();
        map.forEach((key, value) -> {
            String newkey = keyFunc.apply(key);
            if ((value instanceof List)) {
                resultMap.put(newkey, buildValueList((List)value, (m) -> generalMapProcess(m, keyFunc)));
            } else if (value instanceof Map) {
                Map<String, Object> subResultMap = generalMapProcess((Map)value, keyFunc);
                resultMap.put(newkey, subResultMap);
            } else {
                resultMap.put(newkey, value);
            }
        });
        return resultMap;
    }

    public static void main(String[] args) {
        String amap =
            "{\"Ratelimiting\":[{\"id\":9,\"user_name\":\"宋妍霏\",\"user_phone\":\"1433\",\"user_email\":\"137xxxx72@qq.com\"},{\"id\":10,\"user_name\":\"刘闻钦\",\"user_phone\":\"14334455\",\"user_email\":\"abcd_test_xxx@163.com\"}],\"CircuitBreaker\":[{\"id\":9,\"user_name\":\"宋妍霏\",\"user_phone\":\"1433\",\"user_email\":\"13743****2@qq.com\"},{\"id\":10,\"user_name\":\"刘闻钦\",\"user_phone\":\"14334455\",\"user_email\":\"abcsdfa_234@163.com\"}]}";
        Gson gson = new GsonBuilder().create();
        Map map = generalMapProcess(gson.fromJson(amap, Map.class), TransferUtil::keyIntegerToString);
        System.out.println("map = " + map);
    }

}